package ebcs.scan.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import ebcs.scan.bean.common.ExcleEntity;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException; 
@Service
public class ExportDataUtil  {
	private String fileName = "";
	private String filePath = ""; 
	private int countnumb = 65000;
    private Logger logger = Logger.getLogger(ExportDataUtil.class );
    
    public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	  
    
    /** *//**
	 * 导出数据为XLS格式
	 * @param operid      用户名，按用户工号分文件夹导出文件信息
	 * @param list        第一个对象为Excel对象.第二个对象包括表头。
	 */
	public int exportExcel(ExcleEntity excleBean,List reportList) {
		WritableWorkbook wwb;
		FileOutputStream fos;
		String reportTitle =excleBean.getTitle(); 
		String fileName =  excleBean.getFileName();   
		Map<Object,String> excelMap  = excleBean.getHeadMap();
		try {     
			String filePath=excleBean.getPath()+"/downFile/";
			File file = new File(filePath);
			if (file.exists() == false) 	file.mkdirs();
			File fileObject = new File(filePath+"//"+fileName);
			if(fileObject.exists()&&fileObject.delete()==false) {
				return 0; //如果文件存在，而且删除失败。 
			}
			fos = new FileOutputStream(filePath+"//"+fileName,true);
			wwb = Workbook.createWorkbook(fos);  //创建excle 表单
			int fileLength = reportList.size();//文件的总行数
			Object[] headFields = null;
			if(fileLength>0){
 				Set mapItem = excelMap.keySet();
				headFields = mapItem.toArray();
			}
			
			for (int k = 0; k < (fileLength / this.countnumb) + 1; k++) {
 				WritableSheet sheet = wwb.createSheet("sheet" + (k + 1), 500); // 创建一个工作表
				// 设置单元格的文字格式
				WritableFont wf = new WritableFont(WritableFont.ARIAL, 30,WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
				WritableCellFormat wcf = new WritableCellFormat(wf);
				wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
				wcf.setAlignment(Alignment.CENTRE);
				sheet.mergeCells(0, 0, headFields.length, 0);
				sheet.addCell(new Label(0, 0, reportTitle, wcf));// 写表头
				for (int i = -1; i < headFields.length; i++) {// 画表头
					if (i == -1) {
						wcf = new WritableCellFormat();
						wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
						wcf.setAlignment(Alignment.CENTRE);
						wcf.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.HAIR); // 线的样式
						sheet.addCell(new Label(0, 1, "序号", wcf));
					} else {
						sheet.addCell(new Label(i + 1, 1,excelMap.get(headFields[i]), wcf));
						sheet.setColumnView(i + 1, 20);
					}
				}
				// 填充数据的内容
				int size = (k + 1) * this.countnumb; // 表单中的记录数
				if (k == (fileLength / this.countnumb)) {
					size = (k) * this.countnumb + (fileLength % this.countnumb);
				}
				String filedValue = "";
				for (int i = k * this.countnumb; i < size; i++) {
					Map reportMap = (Map) transBean2Map(reportList.get(i));
					for (int j = -1; j < headFields.length; j++) {
						if (j == -1) {
							sheet.addCell(new Label(j + 1, i + 2 - k* this.countnumb, String.valueOf(i + 1 - k* this.countnumb), wcf));
							continue;
						}
						if(reportMap.get(String.valueOf(headFields[j]))==null){
							filedValue="";
						}else{
							filedValue = String.valueOf(reportMap.get(String.valueOf(headFields[j])));
						} 
						sheet.addCell(new Label(j + 1, i + 2 - k* this.countnumb, filedValue, wcf));
					}
				}
			}
			wwb.write();
			wwb.close();
			fos.close();
			//将报表文件夹文件移到临时文件下面
			return 1;
		} catch (IOException e){ e.printStackTrace();
		} catch (RowsExceededException e){e.printStackTrace();
		} catch (WriteException e){e.printStackTrace();}
		return 1;
	}
	public static void main(String[] args) throws ParseException  {
		ExportDataUtil excel = new ExportDataUtil();
		ExcleEntity excleBean = new ExcleEntity();
		excleBean.setFileName("excleFile.xls");
		excleBean.setTitle("excelTitle");
		ArrayList reportList = new ArrayList();
		Map param1 = new HashMap();
		param1.put("filedTitle1", "filedValue1");
		param1.put("filedTitle2", "filedValue2");
		param1.put("filedTitle3", "filedValue3");
		reportList.add(param1);
		excel.exportExcel(excleBean, reportList);
		
	}
	
	// Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
	public Map<String, Object> transBean2Map(Object obj) 
	{
		 Map<String, Object> map = new HashMap<String, Object>();
			java.lang.reflect.Field[] fileds = obj.getClass().getDeclaredFields();
			for(int i=0;i<fileds.length;i++){
				String key = fileds[i].getName();
				Method getter;
				try {
					getter = obj.getClass().getMethod("get"+key.substring(0, 1).toUpperCase()+key.substring(1));
					map.put(key,String.valueOf(getter.invoke(obj)==null?"":getter.invoke(obj)));
				} catch (Exception e) {
					logger.error("error to export excle"+e.getMessage());
					e.printStackTrace(); 
				}  
			 }
		return map;

	}

	
}
